package com.sduept.nwld.dataserver.controller.statistics;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.faces.context.FacesContext;

import com.sduept.bigdata.fault.entity.FaultRecord;
import com.sduept.bigdata.fault.manager.FaultRecordQueryManager;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.nwld.dataserver.manager.statistics.FaultTimeAnalysisCountManager;
import com.sduept.nwld.dataserver.manager.statistics.FaultTimeAnalysisManager;
import com.sduept.nwld.dataserver.manager.statistics.StatisticsCommonManager;
import com.sduept.nwld.dataserver.model.countanalyse.AbstractStatisticsModel;
import com.sduept.nwld.dataserver.model.faulttimeanalysis.BreakerActTimeCount;
import com.sduept.nwld.dataserver.model.faulttimeanalysis.FaultContinuedTimeCount;
import com.sduept.nwld.dataserver.model.faulttimeanalysis.ProtectActTimeCount;

@Named
@ViewScoped
public class FaultTimeAnalysisController extends AbstractController {

	private static final long serialVersionUID = -8699515666477048984L;

	@Autowired
	private StatisticsCommonManager commonM;
	@Autowired
	private FaultTimeAnalysisManager manager;
	@Autowired
	private FaultTimeAnalysisCountManager countM;
	@Autowired
	private FaultRecordQueryManager faultManger;

	private Integer voltage = 0;

	private List<Integer> months = new ArrayList<Integer>();
	private List<Integer> voltages = new ArrayList<Integer>();
	private List<String> subCompanys = new ArrayList<String>();

	// 数据维护页面
	private Integer mYear;
	private Integer mMonth;
	private Integer mVoltage = 0;
	private Integer queryType = 1;// 0是年指标 1是月指标
	private String subCompany;

	/**
	 * 统计结果
	 */
	// 故障持续时间
	private List<FaultContinuedTimeCount> faultTimeCounts = new ArrayList<>();
	private FaultContinuedTimeCount selectFaultTimeCount = new FaultContinuedTimeCount();
	// 保护动作时间
	private List<ProtectActTimeCount> protectActTimeCounts = new ArrayList<>();
	private ProtectActTimeCount selectProtectActTimeCount = new ProtectActTimeCount();
	// 断路器动作时间
	private List<BreakerActTimeCount> breakerActTimeCounts = new ArrayList<>();
	private BreakerActTimeCount selectBreakerActTimeCount = new BreakerActTimeCount();

	private AvgTime avgTimeSelect = null;
	private List<AvgTime> avgTimeTable = new ArrayList<AvgTime>();
	private Map<String, List<Object>> detail = new HashMap<String, List<Object>>();
	private DecimalFormat df = new DecimalFormat("#0.00");
	private Float startTimeLength;
	private Float endTimeLength;
	private boolean colorStatus = true;// 点过滤是true 重置是false
	
	//chart页面传参用
	private int chartStartYear;
	private int chartEndYear;
	private int chartVoltage;

	@PostConstruct
	public void init() {
		for (int i = 1; i <= 12; i++) {
			months.add(i);
		}
		voltages = commonM.getVoltages();
		subCompanys = commonM.getSubCompanys();
		faultTimeCounts = manager.findAllFaultContinuedTimeCount();

	}

	private void initQuery() {
		Calendar cal = Calendar.getInstance();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH) + 1;
		mVoltage = voltage;
	}

	/**
	 * 进入数据维护页面时，查询时间默认为当前系统时间
	 */
	public void initFaultTimeData() {
		detail.clear();
		detail = countM.countAllFaultContinuedTimeDetail();
		initQuery();
		faultTimeQuery();
	}

	/**
	 * 进入数据维护页面时，查询时间默认为当前系统时间
	 */
	public void initProtectActTimeData() {
		detail.clear();
		detail = countM.countAllProtectActTimeCountDetail();
		initQuery();
		protectActTimeQuery();
	}

	/**
	 * 进入数据维护页面时，查询时间默认为当前系统时间
	 */
	public void initBreakerTimeData() {
		detail.clear();
		detail = countM.countAllBreakerActTimeCountDetail();
		initQuery();
		breakerActTimeQuery();
	}

	/**
	 * 初始化查询条件
	 */
	private void initQueryCondition() {
		Calendar cal = Calendar.getInstance();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH) + 1;
		mVoltage = 0;
		queryType = 1; // 月指标
		subCompany = "全部";
	}

	public void resetFaultTimeCount() {
		initQueryCondition();
		faultTimeQuery();
	}

	public void resetProtectActTimeCount() {
		initQueryCondition();
		protectActTimeQuery();
	}

	public void resetBreakerActTimeCount() {
		initQueryCondition();
		breakerActTimeQuery();
	}

	/**
	 * 故障持续时间统计信息查询
	 */
	public void faultTimeQuery() {
		String s = "全部".equals(subCompany) ? null : subCompany;
		Integer v = mVoltage == 0 ? null : mVoltage;
		if (queryType == 0) {
			// 查询年指标，
			faultTimeCounts = manager.findYearFaultContinuedTimeCount(mYear, v, s);
		} else {
			// 查询月指标，
			Integer m = mMonth == 0 ? null : mMonth;
			faultTimeCounts = manager.findMonthFaultContinuedTimeCount(mYear, m, v, s);
		}
	}

	/**
	 * 保护动作时间统计信息查询
	 */
	public void protectActTimeQuery() {
		String s = "全部".equals(subCompany) ? null : subCompany;
		Integer v = mVoltage == 0 ? null : mVoltage;
		if (queryType == 0) {
			// 查询年指标，
			protectActTimeCounts = manager.findYearProtectActTimeCount(mYear, v, s);
		} else {
			// 查询月指标，
			Integer m = mMonth == 0 ? null : mMonth;
			protectActTimeCounts = manager.findMonthProtectActTimeCount(mYear, m, v, s);
		}
	}

	/**
	 * 断路器动作时间统计信息查询
	 */
	public void breakerActTimeQuery() {
		String s = "全部".equals(subCompany) ? null : subCompany;
		Integer v = mVoltage == 0 ? null : mVoltage;
		if (queryType == 0) {
			// 查询年指标，
			breakerActTimeCounts = manager.findYearBreakerActTimeCount(mYear, v, s);
		} else {
			// 查询月指标，
			Integer m = mMonth == 0 ? null : mMonth;
			breakerActTimeCounts = manager.findMonthBreakerActTimeCount(mYear, m, v, s);
		}
	}

	public void selectQueryYear() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> map = context.getExternalContext().getRequestParameterMap();
		String y = map.get("mYear").toString();
		mYear = Integer.valueOf(y);
	}

	public void selectFaultQueryYear() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> map = context.getExternalContext().getRequestParameterMap();
		String y = map.get("mYear").toString();
		mYear = Integer.valueOf(y);
	}

	public void selectProtectQueryYear() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> map = context.getExternalContext().getRequestParameterMap();
		String y = map.get("mYear").toString();
		mYear = Integer.valueOf(y);
	}

	public void selectBreakerQueryYear() {
		FacesContext context = FacesContext.getCurrentInstance();
		Map<String, String> map = context.getExternalContext().getRequestParameterMap();
		String y = map.get("mYear").toString();
		mYear = Integer.valueOf(y);
	}

	public void deleteFaultTimeCount() {
		manager.deleteFaultContinuedTimeCount(selectFaultTimeCount.getId());
	}

	public void deleteProtectActCount() {
		manager.deleteProtectActTimeCount(selectProtectActTimeCount.getId());
	}

	public void deleteBreakerActCount() {
		manager.deleteBreakerActTimeCount(selectBreakerActTimeCount.getId());
	}

	public void countFaultTime() {
		Calendar cal = Calendar.getInstance();
		int currentYear = cal.get(Calendar.YEAR);
		int currentMonth = cal.get(Calendar.MONTH) + 1;
		if (mYear > currentYear) {
			addErrorMessage("请选择合适的年份！");
			return;
		}
		if (0 == queryType) {
			// 统计年指标
			manager.deleteFaultCount(mYear, null);
			for (Integer vol : voltages) {
				countM.countFaultContinuedTime(mYear, null, vol);
			}
		} else if (1 == queryType) {
			// 统计月指标
			manager.deleteFaultCount(mYear, mMonth);
			for (Integer vol : voltages) {
				if (0 == mMonth) {
					if (mYear == currentYear) {
						// 如果为当前年，统计1-当前月的
						for (Integer i = 1; i <= currentMonth; i++) {
							countM.countFaultContinuedTime(mYear, i, vol);
						}
					} else {
						// 如果为历史年，统计1-12月份
						for (Integer month : months) {
							countM.countFaultContinuedTime(mYear, month, vol);
						}
					}
				} else {
					countM.countFaultContinuedTime(mYear, mMonth, vol);

				}
			}
		}
		addSuccessMessage("自动统计完成！");

		faultTimeQuery();
	}

	public void countProtectActTime() {
		Calendar cal = Calendar.getInstance();
		int currentYear = cal.get(Calendar.YEAR);
		int currentMonth = cal.get(Calendar.MONTH) + 1;
		if (mYear > currentYear) {
			addErrorMessage("请选择合适的年份！");
			return;
		}
		if (0 == queryType) {
			// 统计年指标
			manager.deleteProtectActTimeCount(mYear, null);
			for (Integer vol : voltages) {
				countM.countProtectActTimeCount(mYear, null, vol);
			}
		} else if (1 == queryType) {
			// 统计月指标
			manager.deleteProtectActTimeCount(mYear, mMonth);
			for (Integer vol : voltages) {
				if (0 == mMonth) {
					if (mYear == currentYear) {
						// 如果为当前年，统计1-当前月的
						for (Integer i = 1; i <= currentMonth; i++) {
							countM.countProtectActTimeCount(mYear, i, vol);
						}
					} else {
						// 如果为历史年，统计1-12月份
						for (Integer month : months) {
							countM.countProtectActTimeCount(mYear, month, vol);
						}
					}
				} else {
					countM.countProtectActTimeCount(mYear, mMonth, vol);
				}
			}
		}
		addSuccessMessage("自动统计完成！");
		protectActTimeQuery();
	}

	public void countBreakerActTime() {
		Calendar cal = Calendar.getInstance();
		int currentYear = cal.get(Calendar.YEAR);
		int currentMonth = cal.get(Calendar.MONTH) + 1;
		if (mYear > currentYear) {
			addErrorMessage("请选择合适的年份！");
			return;
		}
		if (0 == queryType) {
			// 统计年指标
			manager.deleteBreakerActTimeCount(mYear, null);
			for (Integer vol : voltages) {
				countM.countBreakerActTimeCount(mYear, null, vol);
			}
		} else if (1 == queryType) {
			// 统计月指标
			manager.deleteBreakerActTimeCount(mYear, mMonth);
			for (Integer vol : voltages) {
				if (0 == mMonth) {
					if (mYear == currentYear) {
						// 如果为当前年，统计1-当前月的
						for (Integer i = 1; i <= currentMonth; i++) {
							countM.countBreakerActTimeCount(mYear, i, vol);
						}
					} else {
						// 如果为历史年，统计1-12月份
						for (Integer month : months) {
							countM.countBreakerActTimeCount(mYear, month, vol);
						}
					}
				} else {
					countM.countBreakerActTimeCount(mYear, mMonth, vol);
				}
			}
		}
		addSuccessMessage("自动统计完成！");
		breakerActTimeQuery();
	}

	public void countAllFaultTime() {
		manager.deleteAllFaultCount();
		countM.countAllFaultContinuedTime();
		addSuccessMessage("自动统计完成！");
	}

	public void countAllProtectActTime() {// 保护动作时间
		manager.deleteAllProtectActTime();
		countM.countAllProtectActTimeCount();
		addSuccessMessage("自动统计完成！");
	}

	public void countAllBreakerActTime() {// 断路器动作时间
		manager.deleteAllbreakerActTime();
		countM.countAllBreakerActTimeCount();
		addSuccessMessage("自动统计完成！");
	}

	public void saveFaultTimeCount() {
		selectFaultTimeCount.setStatus(1); // 人工创建或修改的
		manager.createOrUpdate(selectFaultTimeCount);
	}

	public void saveProtectActCount() {
		selectProtectActTimeCount.setStatus(1); // 人工创建或修改的
		manager.createOrUpdateAct(selectProtectActTimeCount);
	}

	public void saveBreakerActCount() {
		selectBreakerActTimeCount.setStatus(1); // 人工创建或修改的
		manager.createOrUpdateBreakerAct(selectBreakerActTimeCount);
	}

	/**
	 * 查看故障平均时长详细   故障持续时间页的dialog detail
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public void avgTimeDetail(FaultContinuedTimeCount avgTime) throws InstantiationException, IllegalAccessException {
		AbstractStatisticsModel model = avgTime;
		getAvgTimeDetail(model);

	}

	/**
	 * 查看保护动作时间详细   保护动作时间页的dialog detail
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public void protectTimeDetail(ProtectActTimeCount avgTime) throws InstantiationException, IllegalAccessException {
		AbstractStatisticsModel model = avgTime;
		getAvgTimeDetail(model);
	}

	/**
	 * 断路器动作时间
	 * @param avgTime
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public void breakerActTimeDetail(BreakerActTimeCount avgTime) throws InstantiationException, IllegalAccessException {
		AbstractStatisticsModel model = avgTime;
		getAvgTimeDetail(model);

	}

	/**
	 * 每个tab页的平均时间详细都调用这个方法完成
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	private void getAvgTimeDetail(AbstractStatisticsModel avgTime) throws InstantiationException, IllegalAccessException {
		startTimeLength = null;
		endTimeLength = null;
		avgTimeTable = new ArrayList<AvgTime>();
		for (String company : detail.keySet()) {
			if (!avgTime.getSubCompany().equals(company)) {
				continue;
			}
			List<Object> compList = detail.get(company);
			Object[] test = compList.toArray();
			if (null != compList) {
				int totalTime = 0; // 故障持续时间总和(微秒)
				int num = 0; // 个数
				for (Object object : test) {
					Object[] obj = (Object[]) object;
					int time = objectTransToInteger(obj[3]);
					totalTime += time;
					num++;
				}
				Float getAvgTime = null;
				if (num != 0) {
					// 将微秒转为毫秒
					String faultTimeAve = df.format((float) totalTime / (1000 * num));
					getAvgTime = Float.parseFloat(faultTimeAve);
				}
				for (Object object : compList) {
					Object[] obj = (Object[]) object;
					if (0 == queryType) {// 年指标
						if (obj[0].toString().contains(avgTime.getYear().toString())) {
							AvgTime at = getAvgTimeClass(company, obj);
							avgTimeTable.add(at);
						}
					} else if (1 == queryType) {
						StringBuilder build = new StringBuilder(avgTime.getYear().toString() + "-");
						if (avgTime.getMonth().toString().length() == 1) {
							build.append("0");
						}
						build.append(avgTime.getMonth().toString());
						if (obj[0].toString().equals(build.toString())) {
							AvgTime at = getAvgTimeClass(company, obj);
							avgTimeTable.add(at);
						}
					}
				}
			}
			break;
		}
	}

	private AvgTime getAvgTimeClass(String company, Object[] obj) {
		String faultId = obj[4].toString();
		FaultRecord fault = faultManger.findById(faultId);
		AvgTime at = new AvgTime();
		at.setCompany(company);
		at.setDate(fault.getFaultTime().toString());
		at.setVoltage((Short) obj[2]);
		Float firstFault = Float.valueOf(obj[3].toString());
		firstFault = firstFault / 1000;
		BigDecimal bd = new BigDecimal(firstFault);
		firstFault = bd.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
		at.setFirstFault(firstFault);
		at.setFaultType(fault.getFaultType());
		at.setFaultReason(fault.getFaultReson());
		at.setFaultPhase(fault.getFaultPhase());
		at.setEquipment(fault.getEquipment());
		return at;
	}

	private int objectTransToInteger(Object obj) {
		String str = obj.toString();
		Double d = Double.parseDouble(str);
		return d.intValue();
	}

	/**
	 * 过滤时长
	 */
	public void reset() {
		colorStatus = false;
		startTimeLength = null;
		endTimeLength = null;
	}

	public void search() {
		colorStatus = true;

	}

	/**
	 * 内部类 展示断路器故障时间平均值
	 * @author xu
	 *
	 */
	public class AvgTime {

		String company;
		String date;
		Short voltage;
		Float firstFault;
		String faultType;
		String faultReason;
		String faultPhase;
		String equipment;

		public AvgTime() {
			super();
			// TODO Auto-generated constructor stub
		}

		public AvgTime(String company, String date, Short voltage, Float firstFault) {
			super();
			this.company = company;
			this.date = date;
			this.voltage = voltage;
			this.firstFault = firstFault;
		}

		public String getCompany() {
			return company;
		}

		public void setCompany(String company) {
			this.company = company;
		}

		public String getDate() {
			return date;
		}

		public void setDate(String date) {
			this.date = date;
		}

		public Short getVoltage() {
			return voltage;
		}

		public void setVoltage(Short voltage) {
			this.voltage = voltage;
		}

		public Float getFirstFault() {
			return firstFault;
		}

		public void setFirstFault(Float firstFault) {
			this.firstFault = firstFault;
		}

		public String getFaultType() {
			return faultType;
		}

		public void setFaultType(String faultType) {
			this.faultType = faultType;
		}

		public String getFaultReason() {
			return faultReason;
		}

		public void setFaultReason(String faultReason) {
			this.faultReason = faultReason;
		}

		public String getFaultPhase() {
			return faultPhase;
		}

		public void setFaultPhase(String faultPhase) {
			this.faultPhase = faultPhase;
		}

		public String getEquipment() {
			return equipment;
		}

		public void setEquipment(String equipment) {
			this.equipment = equipment;
		}

	}

	public Integer getVoltage() {
		return voltage;
	}

	public void setVoltage(Integer voltage) {
		this.voltage = voltage;
	}

	public List<Integer> getMonths() {
		return months;
	}

	public void setMonths(List<Integer> months) {
		this.months = months;
	}

	public List<Integer> getVoltages() {
		return voltages;
	}

	public void setVoltages(List<Integer> voltages) {
		this.voltages = voltages;
	}

	public List<String> getSubCompanys() {
		return subCompanys;
	}

	public void setSubCompanys(List<String> subCompanys) {
		this.subCompanys = subCompanys;
	}

	public Integer getmYear() {
		return mYear;
	}

	public void setmYear(Integer mYear) {
		this.mYear = mYear;
	}

	public Integer getmMonth() {
		return mMonth;
	}

	public void setmMonth(Integer mMonth) {
		this.mMonth = mMonth;
	}

	public Integer getmVoltage() {
		return mVoltage;
	}

	public void setmVoltage(Integer mVoltage) {
		this.mVoltage = mVoltage;
	}

	public Integer getQueryType() {
		return queryType;
	}

	public void setQueryType(Integer queryType) {
		this.queryType = queryType;
	}

	public String getSubCompany() {
		return subCompany;
	}

	public void setSubCompany(String subCompany) {
		this.subCompany = subCompany;
	}

	public List<FaultContinuedTimeCount> getFaultTimeCounts() {
		return faultTimeCounts;
	}

	public void setFaultTimeCounts(List<FaultContinuedTimeCount> faultTimeCounts) {
		this.faultTimeCounts = faultTimeCounts;
	}

	public FaultContinuedTimeCount getSelectFaultTimeCount() {
		return selectFaultTimeCount;
	}

	public void setSelectFaultTimeCount(FaultContinuedTimeCount selectFaultTimeCount) {
		this.selectFaultTimeCount = selectFaultTimeCount;
	}

	public List<ProtectActTimeCount> getProtectActTimeCounts() {
		return protectActTimeCounts;
	}

	public void setProtectActTimeCounts(List<ProtectActTimeCount> protectActTimeCounts) {
		this.protectActTimeCounts = protectActTimeCounts;
	}

	public ProtectActTimeCount getSelectProtectActTimeCount() {
		return selectProtectActTimeCount;
	}

	public void setSelectProtectActTimeCount(ProtectActTimeCount selectProtectActTimeCount) {
		this.selectProtectActTimeCount = selectProtectActTimeCount;
	}

	public List<BreakerActTimeCount> getBreakerActTimeCounts() {
		return breakerActTimeCounts;
	}

	public void setBreakerActTimeCounts(List<BreakerActTimeCount> breakerActTimeCounts) {
		this.breakerActTimeCounts = breakerActTimeCounts;
	}

	public BreakerActTimeCount getSelectBreakerActTimeCount() {
		return selectBreakerActTimeCount;
	}

	public void setSelectBreakerActTimeCount(BreakerActTimeCount selectBreakerActTimeCount) {
		this.selectBreakerActTimeCount = selectBreakerActTimeCount;
	}

	public AvgTime getAvgTimeSelect() {
		return avgTimeSelect;
	}

	public void setAvgTimeSelect(AvgTime avgTimeSelect) {
		this.avgTimeSelect = avgTimeSelect;
	}

	public List<AvgTime> getAvgTimeTable() {
		return avgTimeTable;
	}

	public void setAvgTimeTable(List<AvgTime> avgTimeTable) {
		this.avgTimeTable = avgTimeTable;
	}

	public boolean isColorStatus() {
		return colorStatus;
	}

	public void setColorStatus(boolean colorStatus) {
		this.colorStatus = colorStatus;
	}

	public Float getEndTimeLength() {
		return endTimeLength;
	}

	public void setEndTimeLength(Float endTimeLength) {
		this.endTimeLength = endTimeLength;
	}

	public Float getStartTimeLength() {
		return startTimeLength;
	}

	public void setStartTimeLength(Float startTimeLength) {
		this.startTimeLength = startTimeLength;
	}

	public int getChartStartYear() {
		return chartStartYear;
	}

	public void setChartStartYear(int chartStartYear) {
		this.chartStartYear = chartStartYear;
	}

	public int getChartEndYear() {
		return chartEndYear;
	}

	public void setChartEndYear(int chartEndYear) {
		this.chartEndYear = chartEndYear;
	}

	public int getChartVoltage() {
		return chartVoltage;
	}

	public void setChartVoltage(int chartVoltage) {
		this.chartVoltage = chartVoltage;
	}

}
